import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:home_framework/interfaces/dynamic_listener.dart';
import 'package:home_framework/models/dynamic_entity.dart';
import 'package:home_framework/routers/fluro_router.dart';
import 'package:home_framework/utils/dialogs.dart';
import 'api/dynamic_service.dart';
import 'dynamic_item.dart';
import 'package:get_it/get_it.dart';

class DynamicPage extends StatefulWidget {
  DynamicPage({Key key}) : super(key: key);

  @override
  _DynamicPageState createState() => _DynamicPageState();
}

class _DynamicPageState extends State<DynamicPage> implements DynamicListener {
  List<DynamicEntity> _listItems = [];
  int _currentPage = 1;
  static const int PAGE_SIZE = 20;

  EasyRefreshController _refreshController = EasyRefreshController();

  void _refresh() async {
    _currentPage = 1;
    _requestNewItems();
  }

  void _load() async {
    _currentPage += 1;
    _requestNewItems();
  }

  @override
  void initState() {
    super.initState();
    GetIt.instance.registerSingleton<DynamicListener>(this);
  }

  void dynamicUpdated(String id, DynamicEntity updatedDynamic) {
    int index = _listItems.indexWhere((element) => element.id == id);
    if (index != -1) {
      setState(() {
        _listItems[index] = updatedDynamic;
      });
    }
  }

  void dynamicAdded(DynamicEntity newDynamic) {
    setState(() {
      _listItems.insert(0, newDynamic);
    });
  }

  void _requestNewItems() async {
    var response = await DynamicService.list(_currentPage, PAGE_SIZE);
    if (response != null && response.statusCode == 200) {
      List<dynamic> _jsonItems = response.data;
      List<DynamicEntity> _newItems =
          _jsonItems.map((json) => DynamicEntity.fromJson(json)).toList();
      this.setState(() {
        if (_currentPage > 1) {
          _listItems += _newItems;
        } else {
          _listItems = _newItems;
        }
      });
    }
  }

  void _onItemDelete(String id) async {
    var response = await DynamicService.delete(id);
    if (response.statusCode == 200) {
      setState(() {
        _listItems.removeWhere((element) => element.id == id);
      });
    } else {
      Dialogs.showInfo(this.context, response.statusMessage);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('动态', style: Theme.of(context).textTheme.headline4),
        actions: [
          IconButton(
              icon: Icon(Icons.add),
              onPressed: () {
                RouterManager.router
                    .navigateTo(context, RouterManager.dynamicAddPath);
              }),
          IconButton(
              icon: Icon(Icons.link),
              onPressed: () {
                RouterManager.router
                    .navigateTo(context, RouterManager.datingPath);
              }),
        ],
        brightness: Brightness.dark,
      ),
      body: EasyRefresh(
        controller: _refreshController,
        firstRefresh: true,
        onRefresh: () async {
          _refresh();
        },
        onLoad: () async {
          _load();
        },
        child: ListView.builder(
            itemCount: _listItems.length,
            itemBuilder: (context, index) {
              return DynamicItem(_listItems[index], _onItemDelete);
            }),
      ),
    );
  }
}
